﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;
using CommonLibrary;
using WFControlLibrary;
// 然后发起请求

namespace 任务状态
{
    public partial class Form1 : Form
    {
        public static Boolean run = true,rebush=false,rebush_ui=false;
        private float data = 0, data1 = 0, expect_value = 0, profit_value = 0, alarm_value = 0;
        private static String context = "";
        private static String gp = "sz000519";
        private static int data_i = 0, data1_i = 0;
        private static SparklineChart sparklineChart;
        private static String source_url = "https://qt.gtimg.cn/q=";
        private ProgressBarDrawer progressBarDrawer;
        private static bool exceeding_alert = false;
        private ProgressBarDrawer progressBarDrawer1;
        private DrawDataPic drawDataPic;
        private StockDataSaver stockDataSaver;
        private Buy buy;
        FileAppender fileAppender;
        static ULog log;
        byte DebugSet = 0xff;
        private DateTime lastNotificationDate = DateTime.MinValue; // 记录上一次通知的日期
        private String status = "⏳";
        CustomTrackBar trackBar1 = new CustomTrackBar();
        private Icon icon = null,black_icon=null;
        private bool isBlinking=true;
        private Bitmap bitmap_pic=new Bitmap(96,96);
        private CandleStickChart candleStickChart;
        private static Color[] color = new Color[6]
        {
            Color.Red,      // 第一个颜色：红色
            Color.Green,    // 第二个颜色：绿色
            Color.Blue,     // 第三个颜色：蓝色
            Color.Yellow,    // 第四个颜色：黄色
            System.Drawing.SystemColors.GrayText,
            SystemColors.Control
        };
        public Form1()
        {
            this.DoubleBuffered = true;  // 启用双缓冲
            InitializeComponent();
        }
        private string GetHTMLByURLRequest(string URL)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            WebRequest.DefaultWebProxy = null;
            WebRequest request = WebRequest.Create(URL);
            WebResponse resp = request.GetResponse();
            Stream stream = resp.GetResponseStream();
            StreamReader sr = new StreamReader(stream, Encoding.Default);
            string result = sr.ReadToEnd();
            stream.Close();
            sr.Close();
            return result;
        }

    
        private void DownLoad()
        {
            int count = 100;
            while (run)
            {
                Thread.Sleep(100);
                if (count++ > 100)
                {
                    count = 0;
                    if (Tools.FetchStockDataBefore() || checkBox1.Checked)
                    {
                        try
                        {
                            status = "⏳";
                            Console.WriteLine("正在获取数据:" + source_url + gp);
                            String rest = GetHTMLByURLRequest(source_url + gp);
                            Console.WriteLine("获取到数据:" + rest);
                            if (Tools.FetchStockData())
                            {
                                stockDataSaver.SaveData(gp, rest);
                                status = "🔴";
                            }
                            else
                            {
                                status = "⛔";
                            }
                            if (context != rest)
                            {
                                context = rest;
                                rebush = true;
                                status = "⚡";
                            }
                            else
                            {
                                Console.WriteLine("数据没变不更新处理");
                            }
                        }
                        catch (Exception E)
                        {
                            status = "⚠️";
                            Console.WriteLine($"{E.Message} at line {new StackTrace(E, true).GetFrame(0)?.GetFileLineNumber()}");
                            log.Error($"{E.Message} at line {new StackTrace(E, true).GetFrame(0)?.GetFileLineNumber()}");
                        }
                    }
                }
            }
        }
        private void SetColorBlockForMenuItem(ToolStripItem i,Color color)
        {
            Bitmap colorBlock = new Bitmap(16, 16);
            using (Graphics g = Graphics.FromImage(colorBlock))
            {
                g.FillRectangle(new SolidBrush(color), 0, 0, 16, 16);
            }
            i.Image = colorBlock;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            buy = new Buy();
            crate_blackicon();
            stockDataSaver = new StockDataSaver(gp);
            Thread thread = new Thread(DownLoad);
            thread.Start();
            trackBar1.Name = "trackBar1";
            trackBar1.Size = new Size(100, 20); // 20 是自定义的高度
            trackBar1.Maximum = 100;
            trackBar1.Minimum = 25;
            trackBar1.Value = 70;
            trackBar1.Location = new Point(panel7.Width-trackBar1.Width,0);
            trackBar1.ValueChanged += TrackBar1_ValueChanged;
            panel7.Controls.Add(trackBar1);
            ControlIni.Load(this);
            data_i = comboBox2.SelectedIndex;
            data1_i = comboBox3.SelectedIndex;
            label2.Text = data_i.ToString();
            label3.Text = data1_i.ToString();
            this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
            this.comboBox2.SelectedIndexChanged += new System.EventHandler(this.comboBox2_SelectedIndexChanged);
            this.comboBox3.SelectedIndexChanged += new System.EventHandler(this.comboBox3_SelectedIndexChanged);
            if(comboBox1.Text!="")
            {
                gp =comboBox1.Text;
            }else
            {
                comboBox1.Text = gp;
            }
            string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            for (int i = 0; i < color.Length; i++)
            {
                try
                {
                    color[i] = ColorTranslator.FromHtml(ControlIni.Read("MenuItemColor" + i, ColorTranslator.ToHtml(color[i])));
                }catch(Exception)
                {

                }
                SetColorBlockForMenuItem(contextMenuStrip2.Items[i], color[i]);
                contextMenuStrip2.Items[i].Click += ToolStripMenuItem_Click; 
                contextMenuStrip2.Items[i].Tag = i;
            }
            this.BackColor = color[5];
            this.ForeColor = color[4];
            float.TryParse(comboBox2.Text,out data);
            float.TryParse(comboBox3.Text,out data1);
            sparklineChart = new SparklineChart(panel2.Width,panel2.Width,panel2.Height);
            drawDataPic = new DrawDataPic(panel1);
            BitmapToIcon(bitmap_pic, ref icon);
            SetShow(data, data1);
            ToolStripMenuItem parentItem = new ToolStripMenuItem("颜色设置");
            parentItem.DropDown = contextMenuStrip2;  
            contextMenuStrip1.Items.Insert(1,parentItem);
            source_url=ControlIni.Read("src_comboBox1", source_url);
            Console.WriteLine("数据获取源:"+source_url);
            progressBarDrawer = new ProgressBarDrawer(panel3);
            progressBarDrawer1 = new ProgressBarDrawer(panel8);
            progressBarDrawer.SetBar(expect_value, profit_value, color);
            progressBarDrawer1.SetBar(data, data1, color);
            this.Opacity = (float)trackBar1.Value / 100;
            buy.SwitchStock(gp);
            label7.Text = buy.getFunds().ToString("0.00");
            label8.Text = buy.getValue(data).ToString("0.00");
            SystemEvents.PowerModeChanged += OnPowerModeChanged;
            fileAppender = new FileAppender("log.txt");
            log = new ULog();
            log.SetLevel(DebugSet);
            log.SetFormatFlags(Log.LOG_LEVEL | Log.LOG_TIME);
            log.SetDateFormat("HH:mm:ss.fff");
            log.AddOutput((message, color) => Console.WriteLine(message));
            log.AddOutput((message, color) => fileAppender.Append(message + Environment.NewLine));
            candleStickChart = new CandleStickChart(panel9.Width, panel9.Height);
        }
        private void crate_blackicon()
        {
            int width = 32;
            int height = 32;
            using (Bitmap bitmap = new Bitmap(width, height))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.Clear(Color.Transparent);
                }
                BitmapToIcon(bitmap, ref black_icon);
            }
        }
        private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e)
        {
            if (e.Mode == PowerModes.Resume)
            {
                var timer = new System.Windows.Forms.Timer();
                timer1.Enabled = false;
                timer.Interval = 2000;
                Console.WriteLine("唤醒后先关闭UI刷新定时器");
                timer.Tick += (s, args) =>
                {
                    timer.Stop();
                    timer.Dispose();
                    timer1.Enabled = true;
                    Console.WriteLine("唤醒后过两秒使能UI刷新定时器");
                };
                timer.Start();
            }
        }
        private void TrackBar1_ValueChanged(object sender, EventArgs e)
        {
            this.Opacity =(float) trackBar1.Value/100;
        }

        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (sender is ToolStripMenuItem menuItem)
            {
                int index = (int)menuItem.Tag;
                colorDialog1.Color = color[index];
                if (colorDialog1.ShowDialog() == DialogResult.OK)
                {
                    color[index] = colorDialog1.Color;
                    SetColorBlockForMenuItem(contextMenuStrip2.Items[index], color[index]);
                }
            }
            SetShow(data, data1);
            progressBarDrawer.SetBar(expect_value, profit_value, color);
            progressBarDrawer1.SetBar(data, data1, color);
            this.BackColor = color[5];
            this.ForeColor = color[4];
            if (profit_value > 0)
            {
                label4.ForeColor = color[0];
                label9.ForeColor = color[0];
            }
            else
            {
                label4.ForeColor = color[1];
                label9.ForeColor = color[1];
            }
        }
        private void SetShow(float d1,float d2)
        {
            Color bcolor = color[2];
            Color fcolor = color[0];
            if (d2 < 0)
            {
                bcolor = color[3];
                fcolor = color[1];
            }
            drawDataPic.DrawPic(d1, d2, expect_value, profit_value, color,ref bitmap_pic);
            BitmapToIcon(bitmap_pic, ref icon);
            this.Icon = icon;
            panel1.BackgroundImage = bitmap_pic;
            panel1.Invalidate();
            Bitmap chartMap= sparklineChart.AddDataAndGetBitmap(d2, fcolor, bcolor);
            panel2.BackgroundImage = chartMap;
            panel2.Invalidate();
        }
        private void BitmapToIcon(Bitmap bitmap,ref Icon icn)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    Bitmap smallBitmap = new Bitmap(bitmap, new Size(bitmap.Width, bitmap.Height));
                    smallBitmap.Save(ms, ImageFormat.Png); 
                    byte[] pngBytes = ms.ToArray();
                    using (MemoryStream icoStream = new MemoryStream())
                    {
                        icoStream.Write(new byte[] { 0, 0, 1, 0, 1, 0, (byte)bitmap.Width, (byte)bitmap.Height, 0, 0, 1, 0, 32, 0 }, 0, 14);
                        icoStream.WriteByte((byte)(pngBytes.Length & 0xFF));
                        icoStream.WriteByte((byte)((pngBytes.Length >> 8) & 0xFF));
                        icoStream.WriteByte((byte)((pngBytes.Length >> 16) & 0xFF));
                        icoStream.WriteByte((byte)((pngBytes.Length >> 24) & 0xFF));
                        icoStream.Write(new byte[] { 22, 0, 0, 0 }, 0, 4);
                        icoStream.Write(pngBytes, 0, pngBytes.Length);
                        icoStream.Position = 0;
                        icn?.Dispose();
                        icn = new Icon(icoStream);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("Error converting bitmap to icon: " + ex.Message);
                log.Error($"{ex.Message} at line {new StackTrace(ex, true).GetFrame(0)?.GetFileLineNumber()}");
            }
        }
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            data_i = comboBox2.SelectedIndex;
            label2.Text = data_i.ToString();
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ControlIni.Write("record_" + gp, context.Trim());
            label6.Text = comboBox1.SelectedIndex.ToString() ;
            ControlIni.Write("expect_" + gp, textBox1.Text);
            ControlIni.Write("alarm_" + gp, textBox2.Text);
            gp = comboBox1.Text;
            textBox1.Text = ControlIni.Read("expect_" + gp, "0");
            textBox2.Text = ControlIni.Read("alarm_" + gp, "0.5");
            buy.SwitchStock(gp);
            label7.Text = buy.getFunds().ToString("0.00");
            label8.Text = buy.getValue(data).ToString("0.00");
            context=ControlIni.Read("record_" + gp);
            rebush_ui= true;
        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            data1_i = comboBox3.SelectedIndex;
            label3.Text = data1_i.ToString() ;
        }

        private void comboBox1_TextChanged(object sender, EventArgs e)
        {
        }

        private void comboBox1_TextUpdate(object sender, EventArgs e)
        {

        }


        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.ShowInTaskbar = false;
            this.WindowState = FormWindowState.Normal;
            this.Activate();
            this.Show();
        }
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
        }

        private void 退出ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            run = false;
            comboBox2.SelectedIndex = data_i;
            comboBox3.SelectedIndex = data1_i;
            ControlIni.Save(this);
            buy.SaveStock(gp);
            candleStickChart.SaveCompleteSettings();
            for (int i = 0; i < color.Length; i++)
            {
                ControlIni.Write("MenuItemColor" + i, ColorTranslator.ToHtml(color[i]));
            }
            this.Dispose();
        }

        private void notifyIcon1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right) 
            {
                if (contextMenuStrip1.Visible)
                {
                    contextMenuStrip1.Close();  // 如果菜单可见，则关闭
                }
                else
                {
                    contextMenuStrip1.Show(Cursor.Position);  // 如果菜单不可见，则显示
                }
            }
        }
        private void panel2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip2.Show(panel2, new Point(e.X, e.Y));
            }else
            {
                var stats = sparklineChart.GetStatistics();
                string statsText = $"最高: {stats["Max"]:F2}\n最低: {stats["Min"]:F2}\n平均: {stats["Average"]:F2}\n最新: {stats["Latest"]:F2}";
                Label infoLabel = new Label();
                infoLabel.Text = statsText;
                infoLabel.BackColor = Color.LightYellow;
                infoLabel.BorderStyle = BorderStyle.FixedSingle;
                infoLabel.AutoSize = true;
                infoLabel.Location = new Point(e.X, e.Y);
                panel2.Controls.Add(infoLabel);
                var timer = new System.Windows.Forms.Timer();
                timer.Interval = 2000; // 2秒
                timer.Tick += (s, args) =>
                {
                    timer.Stop();
                    timer.Dispose();
                    panel2.Controls.Remove(infoLabel);
                    infoLabel.Dispose();
                };
                timer.Start();
            }
        }

        private void 显示到任务栏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.ShowInTaskbar = true;
            this.WindowState = FormWindowState.Minimized;
            this.Show();
        }
        private bool dragging = false;
        private Point dragCursorPoint;
        private Point dragFormPoint;
        private void panel6_MouseDown(object sender, MouseEventArgs e)
        {
            dragging = true;
            dragCursorPoint = Cursor.Position;
            dragFormPoint = this.Location;
            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip2.Show(panel6, new Point(e.X, e.Y));
            }
        }

        private void panel6_MouseMove(object sender, MouseEventArgs e)
        {
            if (dragging)
            {
                Point diff = Point.Subtract(Cursor.Position, new Size(dragCursorPoint));
                this.Location = Point.Add(dragFormPoint, new Size(diff));
            }
        }

        private void panel6_MouseUp(object sender, MouseEventArgs e)
        {
            dragging = false;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Hide();
            this.ShowInTaskbar = false;
        }
        private void button4_Click(object sender, EventArgs e)
        {
            if (button4.Text == "📌")
            {
                button4.Text = "🔴";
                this.TopMost = true;
            }
            else
            {
                button4.Text = "📌";
                this.TopMost = false;
            }
        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            notifyIcon1_MouseDoubleClick(null, null);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (Tools.FetchStockData())
            {
                MessageBox.Show(buy.BuyStock(gp, data),"交易信息");
                label7.Text = buy.getFunds().ToString("0.00");
                label8.Text = buy.getValue(data).ToString("0.00");
            }
            else
            {
                MessageBox.Show("非交易时间，不允许交易", "信息");
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (Tools.FetchStockData())
            {
                MessageBox.Show(buy.SellStock(gp, data), "交易信息");
                label7.Text = buy.getFunds().ToString("0.00");
                label8.Text = buy.getValue(data).ToString("0.00");
            }else
            {
                MessageBox.Show("非交易时间，不允许交易", "信息");
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                Console.WriteLine("窗体已最小化");
            }
            else if (this.WindowState == FormWindowState.Normal)
            {
                Console.WriteLine("窗体恢复正常状态");
            }
            else if (this.WindowState == FormWindowState.Maximized)
            {
                Console.WriteLine("窗体已最大化");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            
        }

        private void comboBox1_Leave(object sender, EventArgs e)
        {
            if (comboBox1.Text.Length > 0)
            {
                if (!comboBox1.Items.Contains(comboBox1.Text))
                {
                    comboBox1.Items.Add(comboBox1.Text);
                }
            }
            ControlIni.Write("expect_" + gp, textBox1.Text);
            ControlIni.Write("alarm_" + gp, textBox2.Text);
            gp = comboBox1.Text;
            textBox1.Text = ControlIni.Read("expect_" + gp, "0");
            textBox2.Text = ControlIni.Read("alarm_" + gp, "0.5");
            buy.SwitchStock(gp);
            label7.Text = buy.getFunds().ToString("0.00");
            label8.Text = buy.getValue(data).ToString("0.00");
        }

        private void comboBox1_Validated(object sender, EventArgs e)
        {
        }

        private void panel6_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            SystemEvents.PowerModeChanged -= OnPowerModeChanged;
        }

        private void panel5_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            { 
                contextMenuStrip2.Show(panel5, new Point(e.X, e.Y));
            }
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            关于 form = new 关于();
            form.TopMost = this.TopMost;
            form.BackColor = this.BackColor;
            form.ForeColor = this.ForeColor;
            form.Show();
        }

 
        private void 查看当天ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start(@"Tools\历史曲线\历史曲线.exe", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "StockData", gp));
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            textBox1.Enabled = !checkBox2.Checked;
        }
        private (float current, float open, float high, float low)? ParsePriceData(string[] parts)
        {
            if (float.TryParse(parts[3], out float current) &&
                float.TryParse(parts[4], out float open) &&
                float.TryParse(parts[33], out float high) &&
                float.TryParse(parts[34], out float low))
            {
                return (current, open, high, low);
            }
            return null;
        }

        private void CandlestickChart()
        {
            string[] parts = context.Split('~');
            if(parts.Length<34)
            {
                return;
            }
            var prices = ParsePriceData(parts);
            if (prices == null) return;
            float currentPrice = prices.Value.current;
            float openPrice = prices.Value.open;
            float highPrice = prices.Value.high;
            float lowPrice = prices.Value.low;
            candleStickChart.AddDailyData(DateTime.Now, openPrice, highPrice, lowPrice, currentPrice,
                currentPrice > openPrice? color[0]: color[2], 
                currentPrice > openPrice? color[1]: color[3],
                Color.Gray
                );
            panel9.BackgroundImage = candleStickChart.DrawToBitmap();
            panel9.Invalidate();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            label9.Text = status;
            if (icon == null) return;
            if (black_icon == null) return;
            CandlestickChart();
            if (exceeding_alert&& Tools.FetchStockData())
            {

                DateTime currentDate = DateTime.Today;
                if (currentDate != lastNotificationDate)
                {
                    lastNotificationDate = currentDate;
                    Automatic_transactions();
                }
                if (isBlinking)
                {
                    notifyIcon1.Icon = icon;
                }
                else
                {
                    notifyIcon1.Icon = black_icon;
                }
                isBlinking = !isBlinking;
            }else
            {
                notifyIcon1.Icon = icon;
            }
        }

        private void label1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Process.Start(@"Tools\历史曲线\历史曲线.exe", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "StockData", gp));
            }
        }

        private void CheckAndShowNotification(String title,String text)
        {
            notifyIcon1.BalloonTipTitle = title;
            notifyIcon1.BalloonTipText = text;
            notifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
            notifyIcon1.ShowBalloonTip(3000);
        }
        private void Automatic_transactions()
        {
            // 只在交易时间运行
            if (!Tools.FetchStockData()) return;
            if (!checkBox2.Checked) return;
            try
            {
                // 获取当前持仓和资金状态
                double currentPosition = buy.getValue(data);
                double availableFunds = buy.getFunds();
                string msg;

                // 检查是否达到卖出条件（当前价 > 预期值 + 阈值）
                if (data > expect_value + alarm_value && currentPosition > 0)
                {
                    // 确保不是当日买入的（T+1限制）
                    if (buy.BuyDate.Date < DateTime.Today)
                    {
                        msg = buy.SellStock(gp, data);
                        CheckAndShowNotification("自动卖出", msg);
                        log.Release(msg);

                        // 关键修改：将卖出价设为新的预期值
                        expect_value = data;
                        textBox1.Text = expect_value.ToString("0.00");

                        UpdateUI();
                    }
                }
                // 检查是否达到买入条件（当前价 < 预期值 - 阈值）
                else if (data < expect_value - alarm_value && availableFunds >= data)
                {
                    msg = buy.BuyStock(gp, data);
                    CheckAndShowNotification("自动买入", msg);
                    log.Release(msg);
                    UpdateUI();
                }
            }
            catch (Exception ex)
            {
                log.Error($"自动交易出错: {ex.Message}");
            }
        }

        private void UpdateUI()
        {
            // 线程安全更新UI
            if (this.InvokeRequired)
            {
                this.Invoke((MethodInvoker)delegate {
                    label7.Text = buy.getFunds().ToString("0.00");
                    label8.Text = buy.getValue(data).ToString("0.00");
                    // 不再自动修改textBox1（预期值），因为已在卖出逻辑中单独处理
                });
            }
            else
            {
                label7.Text = buy.getFunds().ToString("0.00");
                label8.Text = buy.getValue(data).ToString("0.00");
            }
        }
        private void 更新版本ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string url = "https://gitee.com/zmpty/win_task_status/releases";
            Process.Start(new ProcessStartInfo
            {
                FileName = url,
                UseShellExecute = true
            });
        }

        private void 源ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            源设置 form = new 源设置();
            form.TopMost = this.TopMost;
            form.BackColor = this.BackColor;
            form.ForeColor = this.ForeColor;
            form.Show();
            source_url = ControlIni.Read("src_comboBox1", source_url);
        }

        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip2.Show(panel1, new Point(e.X, e.Y));
            }
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            退出ToolStripMenuItem_Click_1(null, null);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if(rebush|| rebush_ui)
            {
                try
                {
                    var match = Regex.Match(context, "\"([^\"]*)\"");
                    if (match.Success)
                    {
                        string content = match.Groups[1].Value;
                        Console.WriteLine("处理数据:..."+ content);
                        String[] rests = content.Split('~');
                        if (rests == null)
                        {
                            Console.WriteLine("异常数据:" + rests);
                            return;
                        }
                        if (rests.Length <= 1)
                        {
                            Console.WriteLine("异常数据:" + rests.Length);
                            return;
                        }
                        if (data_i < 0)
                        {
                            data_i = 3;
                        }
                        if (data_i >= rests.Length)
                        {
                            Console.WriteLine("异常数据:" + context);
                            return;
                        }
                        if (data1_i < 0)
                        {
                            data1_i = 31;
                        }
                        if (data1_i >= rests.Length)
                        {
                            Console.WriteLine("异常数据:" + context);
                            return;
                        }
                        label3.Text = data_i.ToString();
                        label3.Text = data1_i.ToString();
                        float.TryParse(rests[data_i], out data);
                        float.TryParse(rests[data1_i], out data1);

                        this.Text = rests[1];
                        label5.Text = rests[1];
                        if(rebush==true)label1.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");
                        for (int i = 0; i < rests.Length; i++)
                        {
                            if (comboBox2.Items.Count <= i) comboBox2.Items.Add("null");
                            if (comboBox3.Items.Count <= i) comboBox3.Items.Add("null");
                            comboBox2.Items[i] = rests[i];
                            comboBox3.Items[i] = rests[i];
                        }
                        comboBox2.Text = rests[data_i];
                        comboBox3.Text = rests[data1_i];
                        float a = 0;
                        float b = 0;
                        if (!float.TryParse(textBox1.Text, out b))
                        {
                            textBox1.Text = comboBox2.Text;
                        }
                        if (float.TryParse(comboBox2.Text, out a) && float.TryParse(textBox1.Text, out b))
                        {
                            profit_value = a - b;
                            label4.Text = profit_value.ToString("0.00");
                            notifyIcon1.Text = label4.Text;
                            if (profit_value > 0)
                            {
                                label4.ForeColor = color[0];
                                label9.ForeColor = color[0];
                            }
                            else 
                            {
                                label4.ForeColor = color[1];
                                label9.ForeColor = color[1];
                            }
                            expect_value = b;
                            if (float.TryParse(textBox2.Text, out b))
                            {
                                alarm_value = b;
                                exceeding_alert = (Math.Abs(profit_value) - b)>=0;
                                //if ((Math.Abs(profit_value) - b) < -0.1)
                                //{
                                //    exceeding_alert = false;
                                //    Console.WriteLine("恢复预警 "+ (Math.Abs(profit_value) - b));
                                //}
                                //if (((Math.Abs(profit_value) - b) > 0) && exceeding_alert == false)
                                //{
                                //    exceeding_alert = true;
                                //    notifyIcon1.ShowBalloonTip(1000, profit_value.ToString("0.00"), "提示", ToolTipIcon.Info);
                                //    Console.WriteLine("超出预警 "+ (Math.Abs(profit_value) - b));
                                //}
                            }
                        }
                        progressBarDrawer.SetBar(expect_value, profit_value, color);
                        SetShow(data, data1);
                        progressBarDrawer1.SetBar(data, data1, color);
                        label7.Text = buy.getFunds().ToString("0.00");
                        label8.Text = buy.getValue(data).ToString("0.00");
                    }
                    else
                    {
                        Console.WriteLine("未找到匹配的内容。");
                    }
                    rebush = false;
                    rebush_ui = false;
                }
                catch (Exception E)
                {
                    this.Text = (E.Message);
                    Console.WriteLine($"{E.Message} at line {new StackTrace(E, true).GetFrame(0)?.GetFileLineNumber()}");
                    log.Error($"{E.Message} at line {new StackTrace(E, true).GetFrame(0)?.GetFileLineNumber()}");
                    rebush = false;
                    rebush_ui = false;
                }

            }
        }
    }
}
